{% load cctags %}
{% load ccfilters %}

{% block css %}
    <style>
        #photo_upload_form {
            text-align: center;
        }
        #upload_button {
            position: absolute;
            z-index: 98;
        }
        #file_input {
            display: block;
            position: absolute;
            cursor: pointer;
            opacity: 0;
            filter :alpha(opacity=0);
            z-index: 99;
            width:1px;
        }
        #upload_waiting {
            display: none;
        }
    </style>
{% endblock %}

{% block scripts %}
<script type="text/javascript">
var init_photo_upload = function(opts){
    var photo_upload_callback = opts.photo_upload_callback;
    var error_callback = opts.error_callback;
    var file_input = $("#file_input");
    var upload_button = $("#upload_button");
    var upload_waiting = $("#upload_waiting");

    if (opts.left && opts.top ){
        upload_button.css({
            left: opts.left + "px",
            top: opts.top +"px"
        });
    }

    if (opts.img_type){  // "Photo", "Avatar" or "Map"
        $("#img_type").val(opts.img_type);
    }

    var relocation_fileinput = function() {
        file_input.width(upload_button.width());
        file_input.height(upload_button.height());
        var button_position = upload_button.offset();
        file_input.css({
            left: button_position.left + "px",
            top: button_position.top +"px"
        });
    }
    upload_button.hover( function () {
        relocation_fileinput();
    });

    var check_file_ext = function(filename) {
        var accepted_exts = "jpg,png,gif,jpeg,tiff,ico,bmp,jpe";
        filename = filename.split('.');
        var ext = filename[filename.length-1].toLowerCase();
        return accepted_exts.indexOf(ext) >= 0;
    };
    var check_file_size= function(file_input) {
        if ($.browser.msie){ return true;}
        return (file_input[0].files[0].size  < {{ site_settings.upload_photo_limit }})
    }
    var upload_file = function(){
        var signature = "";
        upload_waiting.show();

        $.getJSON("{{site_settings.host_site}}/apis/rest/?method=get_upload_signature&callback=?")
                .done(function(data){
                    if (data.status=="ok") {
                        signature = data.signature;
                        _upload(signature);
                    } else{
                        alert(data.message);
                        upload_waiting.hide();
                    }
                });

        var _upload = function(signature) {
            $("#signature").val(signature);
            //alert($("#signature").val());
            var getuploadurl = "{{site_settings.depot_site}}/getuploadurl/?signature=" + signature +
                    "&host="+ encodeURI("{{site_settings.host_site}}/apis/rest/");

            $.ajax({
                url: getuploadurl,
                dataType: "script",
                timeout: 5000
            }).done(function(){
                //server response result,uploadurl,message
                if (result=="ok"){
                    //alert(uploadurl);
                    var upload_form = $("#photo_upload_form")[0];
                    upload_form.action = uploadurl;
                    upload_form.submit();

                    //check upload done
                    var check_url = "{{site_settings.depot_site}}/getphotourl/"+signature+"?timeout=2";
                    var start_time = new Date();
                    var timeout = 60000;
                    var interval_control;
                    var running = false;

                    _check_result = function(){
                        if (running){ return; }
                        running = true;
                        uplpoad_request = jQuery.getScript(check_url,
                            function() {
                                if (result=="ok"){
                                    //photourl from server reponse
                                    clearInterval(interval_control);
                                    upload_waiting.hide();
                                    if (photo_upload_callback) {
                                        photo_upload_callback(photourl);
                                    }
                                    return;
                                } else {
                                    running = false;
                                }
                                var now = new Date();
                                if((now - start_time) > timeout){
                                    clearInterval(interval_control);
                                    upload_waiting.hide();
                                    error_callback && error_callback("timeout");
                                    alert('{% _ "upload error" %}');
                                }
                                running = false;
                            }
                        );
                        uplpoad_request.fail = function(jqXHR, textStatus, errorThrown){
                            error_callback && error_callback(textStatus);
                        }
                    }
                    setTimeout("_check_result();", 1000);
                    interval_control = setInterval("_check_result();", 3000);
                } else {
                    if (error_callback){
                        error_callback(message);
                    } else {
                        alert(message);
                    }
                }
            }).fail(function(jqXHR, textStatus, errorThrown){
                error_callback && error_callback(textStatus);
            });
            return false;
        };
        var getphotourl = function(signature) {
            $.getScript("{{site_settings.depot_site}}/getphotourl/"+signature)
                    .done(function() {
                        if (result=="ok"){
                            //var photourl from server reponse
                            if (photo_upload_callback) {
                                photo_upload_callback(photourl);
                            }
                        } else {
                            alert("{% _ 'get photo error' %}");
                        }
                        upload_waiting.hide();
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        alert(textStatus);
                        error_callback && error_callback(textStatus);
                    });
        };
    };
    
    file_input.change( function() {
        if (! file_input.val() ){
            return false;
        }
        if (!check_file_ext(file_input.val())) {
            alert("{% _ 'unsupported file type' %}!");
            return false;
        }
        if (!check_file_size(file_input)) {
            alert("{% _ 'file size exceed' %}! < {{ site_settings.upload_photo_limit|divide:"1048576"|floatformat:"1" }} M");
            return false;
        }
        upload_file();
    });
};
var get_upload_button = function(){
    return $("#upload_button");
};
</script>
{% endblock %}
<iframe name="frame_submit" id="frame_submit"  style="display:none" width="0" height="0"></iframe>
<form id="photo_upload_form" target="frame_submit" method="post" enctype="multipart/form-data">
    <input type="hidden" id="signature" name="signature" value=""/>
    <input type="hidden" id="photo_url" name="photo_url" value=""/>
    <input type="hidden" id="img_type" name="img_type" value="Photo"/>
    <a id="upload_button" href="javascript:;">{% _ "Upload Photo" %}<br/>
        <img id="upload_waiting" src="/static/images/uploading.gif"/></a>
    <input id="file_input" type="file" name="file"/>
</form>
